/*
 * 说说页面组件 - Talks Page Component
 * 展示动态、心情、短文等内容分享功能
 */

import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import { Spin, message, BackTop } from 'antd';
import { VerticalAlignTopOutlined } from '@ant-design/icons';
import TalkPublish from '@/components/TalkPublish';
import TalkCard from '@/components/TalkCard';
import AnonymousUserInfoForm from '@/components/AnonymousUserInfoForm';
import { getTalkList } from '@/services/Talk/api';
import { getAnonymousUserInfo } from '@/services/AnonymousUser/api';
import type { TalkItem } from '@/models/talk';
import { useUserId, useUserIdentity } from '@/hooks';
import styles from './talks.less';

const TalksPage: React.FC = () => {
  const [talks, setTalks] = useState<TalkItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [, setTotal] = useState(0);
  const [showUserInfoForm, setShowUserInfoForm] = useState(false);
  const [userInfoData, setUserInfoData] = useState({
    name: '',
    email: '',
    link: '',
  });
  
  // 获取当前用户ID（登录用户或临时用户）
  const currentUserId = useUserId();
  const identity = useUserIdentity();

  // 检查匿名用户信息
  const checkAnonymousUserInfo = async () => {
    // 如果已登录，不需要检查
    if (identity.isLoggedIn) {
      setShowUserInfoForm(false);
      return;
    }

    // 检查localStorage中是否有信息
    const localName = localStorage.getItem('anonymousUserName');
    const localEmail = localStorage.getItem('anonymousUserEmail');
    const localLink = localStorage.getItem('anonymousUserLink');

    // 如果localStorage中邮箱存在且不为空，不需要请求后端和显示表单
    // 注意：name现在后端会自动生成"游客+ID前12位"，所以主要检查email
    if (localEmail && localEmail.trim()) {
      setShowUserInfoForm(false);
      return;
    }

    // 如果localStorage缺少任一项，需要请求后端检查
    // 如果没有userId，等待生成
    if (!currentUserId) {
      return;
    }

    try {
      // 请求后端检查是否已填写
      const result = await getAnonymousUserInfo(currentUserId);
      
      if (result.data.exists) {
        const { name, email, link } = result.data;
        
        // 如果后端有数据，同步到localStorage
        if (name && name.trim()) {
          localStorage.setItem('anonymousUserName', name);
        }
        if (email && email.trim()) {
          localStorage.setItem('anonymousUserEmail', email);
        }
        if (link && link.trim()) {
          localStorage.setItem('anonymousUserLink', link);
        }

        // 后端会自动生成name（"游客+ID前12位"），所以只需要检查email是否为空
        if (!email || !email.trim()) {
          setShowUserInfoForm(true);
          setUserInfoData({ name: name || '', email: email || '', link: link || '' });
        } else {
          // 邮箱已填写，不显示表单
          setShowUserInfoForm(false);
        }
      } else {
        // 后端不存在记录，显示表单
        setShowUserInfoForm(true);
        setUserInfoData({ name: '', email: '', link: '' });
      }
    } catch (error) {
      console.error('检查匿名用户信息失败:', error);
      // 出错时，如果localStorage没有邮箱信息，显示表单
      if (!localEmail || !localEmail.trim()) {
        setShowUserInfoForm(true);
        setUserInfoData({ name: localName || '', email: localEmail || '', link: localLink || '' });
      }
    }
  };

  // 表单提交成功后的回调
  const handleUserInfoSubmitSuccess = () => {
    setShowUserInfoForm(false);
  };

  // 获取说说列表
  const fetchTalks = async (pageNum: number = 1, append: boolean = false) => {
    if (loading) return;
    
    setLoading(true);
    try {
      const result = await getTalkList({
        page: pageNum,
        size: 10,
      });
      
      if (result && result.code === 200 && result.data) {
        const { list = [], total: totalCount = 0, totalPages = 0 } = result.data;
        
        if (append) {
          setTalks(prev => [...prev, ...list]);
        } else {
          setTalks(list);
        }
        
        setTotal(totalCount);
        setHasMore(pageNum < totalPages);
        setPage(pageNum);
      } else {
        console.error('API 返回数据格式错误:', result);
        message.error('获取说说列表失败：数据格式错误');
      }
    } catch (error) {
      message.error('获取说说列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 加载更多
  const loadMore = () => {
    if (hasMore && !loading) {
      fetchTalks(page + 1, true);
    }
  };

  // 发布成功后刷新列表
  const handlePublishSuccess = () => {
    fetchTalks(1, false);
  };

  // 说说更新后刷新列表
  const handleTalkUpdate = () => {
    fetchTalks(1, false);
  };

  // 滚动加载更多
  const handleScroll = () => {
    const { scrollTop, scrollHeight, clientHeight } = document.documentElement;
    if (scrollTop + clientHeight >= scrollHeight - 100) {
      loadMore();
    }
  };

  useEffect(() => {
    fetchTalks();
  }, []);

  useEffect(() => {
    // 当userId和identity准备好时，检查匿名用户信息
    if (currentUserId) {
      checkAnonymousUserInfo();
    }
  }, [currentUserId, identity.isLoggedIn]);

  useEffect(() => {
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, [page, hasMore, loading]);

  return (
    <PageContainer ghost>
      <div className={styles.container}>
        <div className={styles.header}>
          <h1 className={styles.title}>说说</h1>
          <p className={styles.subtitle}>分享生活的点点滴滴</p>
        </div>
        
        {/* 匿名用户信息表单 */}
        {showUserInfoForm && currentUserId && (
          <AnonymousUserInfoForm
            userId={currentUserId}
            initialName={userInfoData.name}
            initialEmail={userInfoData.email}
            initialLink={userInfoData.link}
            onSubmitSuccess={handleUserInfoSubmitSuccess}
          />
        )}
        
        {/* 发布说说 */}
        <TalkPublish onPublishSuccess={handlePublishSuccess} />
        
        {/* 说说列表 */}
        <div className={styles.talkList}>
          {talks.map((talk) => (
            <TalkCard
              key={talk.id}
              talk={talk}
              currentUserId={currentUserId}
              onUpdate={handleTalkUpdate}
            />
          ))}
          
          {loading && (
            <div className={styles.loading}>
              <Spin size="large" />
              <p>加载中...</p>
            </div>
          )}
          
          {!hasMore && talks.length > 0 && (
            <div className={styles.noMore}>
              <p>没有更多内容了</p>
            </div>
          )}
          
          {!loading && talks.length === 0 && (
            <div className={styles.empty}>
              <p>还没有说说，快来发布第一条吧！</p>
            </div>
          )}
        </div>
        
        {/* 回到顶部 */}
        <BackTop>
          <div className={styles.backTop}>
            <VerticalAlignTopOutlined />
          </div>
        </BackTop>
      </div>
    </PageContainer>
  );
};

export default TalksPage;